package edu.dgut.bbssystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.dgut.bbssystem.common.PageInfo;
import edu.dgut.bbssystem.mapper.UserMapper;
import edu.dgut.bbssystem.pojo.User;
import edu.dgut.bbssystem.service.UserService;
import edu.dgut.bbssystem.common.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public int add(User user){
        int result = Constant.FAIL;
        String userName = user.getUserName();
        boolean b = existUserName(userName);
        //用户名不存在
        if (!b){
            int insert = userMapper.insert(user);
            if (insert>0){
                result = Constant.SUCCESS;
            }
        }else {//用户名已经存在
            result = Constant.USERNAME_EXIST;
        }
        return result;
    }
    @Override
    public boolean existUserName(String userName) {
        User user = userMapper.getByUserName(userName);
        if (user == null){
            return false;
        }
        return true;
    }

    @Override
    public int login(User user, HttpSession session) {
        int code = Constant.FAIL;
        String userName = user.getUserName();
        String password = user.getPassword();
        User u = userMapper.getByUserNameAndPassword(userName, password);
        if (u == null){
            code = Constant.USERNAME_OR_PASSWORD_ERROR;
        }
        else {
            session.setAttribute("user",u);
            code = Constant.SUCCESS;
        }
        return code;
    }

    @Override
    public User getById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public int update(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public PageInfo<User> pageQueryAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<User> apge = userMapper.getAll();
        return new PageInfo(apge);
    }

    @Override
    public int deleteUsersByIds(int[] userIds) {
        int count = userMapper.deleteByIds();
        return Constant.SUCCESS;
    }

    @Override
    public int logout(HttpSession session) {
        Object user = session.getAttribute("user");
        if(user != null){
            session.removeAttribute("user");
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }

    @Override
    public int getUserId(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null){
            return user.getUserId();
        }
        return 0;
    }
}
